package com.rongc.client.freight.business.waybill.view.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.KeyboardUtil;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.model.BaseDic;
import com.rongc.client.freight.base.model.OrderDic;
import com.rongc.client.freight.base.view.activity.HostActivity;
import com.rongc.client.freight.base.view.activity.MapGdActivity;
import com.rongc.client.freight.base.view.widget.BaseInputDialog;
import com.rongc.client.freight.base.view.widget.DividerItemDecoration;
import com.rongc.client.freight.business.carrier.model.ConveyanceDic;
import com.rongc.client.freight.business.mine.view.activity.PasswordPayActivity;
import com.rongc.client.freight.business.mine.view.adapter.RecyclerKeyboardAdapter;
import com.rongc.client.freight.business.mine.view.popup.MinePopup;
import com.rongc.client.freight.business.supply.model.SupplyDic;
import com.rongc.client.freight.business.supply.view.fragment.SupplyFragment;
import com.rongc.client.freight.business.supply.view.fragment.UserFragment;
import com.rongc.client.freight.business.supply.view.popup.SupplyPopup;
import com.rongc.client.freight.business.waybill.model.LogisticsBean;
import com.rongc.client.freight.business.waybill.model.WayBillDetailBean;
import com.rongc.client.freight.business.waybill.view.adapter.RecyclerWaybillAdapter;
import com.rongc.client.freight.business.waybill.view.mvp.QuestionContract;
import com.rongc.client.freight.business.waybill.view.mvp.QuestionPresenter;
import com.rongc.client.freight.utils.UtilMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

import static com.flyco.dialog.widget.NormalDialog.STYLE_TWO;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.CANEL_CZ_STATUS;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.COMPLATE_STATUS;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.DZF_STATUS;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.ROAD_STATUS;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.SH_STATUS;
import static com.rongc.client.freight.business.supply.model.SupplyDic.StatusType.YAJIN_STATUS;

/**
 * Created by ccqx on 2017/7/21.
 */

public class WayBillNewActivity extends BaseActivity implements
        View.OnClickListener,
        QuestionContract.View<WayBillDetailBean>{
    @Bind(R.id.btn_submit)
    Button mBtnSubmit;
    @Bind(R.id.btn_pic)
    Button mBtnPic;
    @Bind(R.id.tv_status)
    TextView mTvStatus;
    @Bind(R.id.tv_total_2)
    TextView mTvTotal2;
    @Bind(R.id.tv_local)
    TextView mTvLocal;
    @Bind(R.id.recycler)
    RecyclerView mRecyclerView;
    @Bind(R.id.tv_total_3)
    TextView mTvTotal3;

    RecyclerWaybillAdapter mLvAdapter;
    List<LogisticsBean> lsNews;

    SupplyFragment supplyFragment;
    UserFragment userFragment;

    PopupWindow popupWindowPay,popupWindowPayWay,popupWindowKeyword;
    NormalDialog caneldialog;
    NormalDialog cashdialog;
    NormalDialog payDialog;
    NormalDialog payResultDialog;
    NormalDialog defineDialog;
    NormalDialog complateDialog;

    BaseInputDialog inputDialog;
    List<String> pwdDatas = new ArrayList<>();

    String waybillId;
    WayBillDetailBean bean;

    int status ;
    String payWay = OrderDic.OrderType.Order_YUE;  // 我的钱包
    String payType = "1";  // 1：货主支付订单  3：车主支付押金
    int showcount ;
    Timer timer = new Timer();
    boolean isrun = false;  // 轮询标识
    boolean isComplate = false;  // 支付成功弹出评论dialog
    QuestionContract.Presenter presenter;

    @OnClick({R.id.tv_local,R.id.btn_submit,R.id.btn_pic,R.id.tv_add})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_status:
                showDialog("caneldialog");
                break;
            case R.id.tv_local:
                jumpMap();
                break;
            case R.id.btn_pic:
                jumpHuidan(); // 上传回单
                break;
            case R.id.tv_add:
                showDialog("inputDialog");
                break;
            case R.id.btn_submit:
                if(status == DZF_STATUS){
                    payType = "1";
                    String price ="";
                    if (bean != null) price = bean.getCostByType();
                    ((TextView) popupWindowPay.getContentView().findViewById(R.id.tv_total)).setText("￥" + price);
                    popupWindowPay.getContentView().findViewById(R.id.tv_tip).setVisibility(View.VISIBLE);
                    showDialog("popupWindowPay");
                }else if(status == YAJIN_STATUS && BaseDic.IdentityType.DRIVING_TYPE.equals(UniApplication.getInstance().getType()) ){
                    showDialog("cashdialog");
                }else if(SupplyDic.getStatusBtn(status).equals("评论")){
                    //  评论
                    jumpReply();
                }else if(status == SH_STATUS){
                    showDialog("defineDialog");
                }else {
                    int status = StringUtils.parseInt(v.getTag().toString());
                    presenter.changeStatus(status+"",waybillId);
                }

                break;
            case R.id.btn_pay:
                //  调用支付 成功后修改状态
                switch (payWay){
                    case OrderDic.OrderType.Order_ALI:
                        presenter.Alipay(payType,waybillId);
                        break;
                    case OrderDic.OrderType.Order_YUE:
                        if(StringUtils.isEmpty(UniApplication.getInstance().getUserInfo().getPayPwd())) {
                            ActivityUtils.startActivity(this, PasswordPayActivity.class);
                            return;
                        }

                        pwdDatas.clear();

                        String cost = "";
                        if("1".equals(payType))
                            cost = bean.getCostByType();
                        else if("3".equals(payType))
                            cost = "100";
                        ((TextView)popupWindowKeyword.getContentView().findViewById(R.id.tv_total)).setText(
                                String.format(getResources().getString(R.string.tixian_popup_total),cost));
                        showDialog("popupWindowKeyword");
                        break;
                    case OrderDic.OrderType.Order_WX:
                        ActivityUtils.toast("暂不支持");
//                        presenter.WxPay(payType,waybillId);
                        break;
                }

                break;
            case R.id.lyt_way:
                showDialog("popupWindowPayWay");
                break;
            case R.id.lyt_wx:
                ((TextView)popupWindowPay.getContentView().findViewById(R.id.tv_pay)).setText("微信");
                payWay = OrderDic.OrderType.Order_WX;
                hideDialog("popupWindowPayWay");
                break;
            case R.id.lyt_zfb:
                ((TextView)popupWindowPay.getContentView().findViewById(R.id.tv_pay)).setText("支付宝");
                payWay = OrderDic.OrderType.Order_ALI;
                hideDialog("popupWindowPayWay");
                break;
            case R.id.lyt_qb:
                ((TextView)popupWindowPay.getContentView().findViewById(R.id.tv_pay)).setText("我的钱包");
                payWay = OrderDic.OrderType.Order_YUE;
                hideDialog("popupWindowPayWay");
                break;
            case R.id.iv_close_way:
                hideDialog("popupWindowPayWay");
                break;
            case R.id.iv_close:
                hideDialog("popupWindowPay");
                hideDialog("popupWindowKeyword");
                break;
            case R.id.tv_forget:
                jumpForgot();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public void initData() {
        if(bean != null) {
            supplyFragment.setData(bean);
            supplyFragment.setListener(this);

            mTvTotal2.setText(Html.fromHtml(String.format(
                    getResources().getString(R.string.waybill_total_lable),bean.getCostByType())));
            mTvTotal3.setText(String.format(getResources().getString(R.string.supply_waybill_total),bean.getCostByType()));
            switch (UniApplication.getInstance().getType()) {
                case BaseDic.IdentityType.OWNER_TYPE:
                    initToolbar(SupplyDic.getStatusTitle(status));
                    mTvStatus.setText(SupplyDic.getStatusStr(status));
                    String btnStr = SupplyDic.getStatusBtn(status);

                    if (StringUtils.isEmpty(btnStr)) mBtnSubmit.setVisibility(View.GONE);
                    else {
                        mBtnSubmit.setVisibility(View.VISIBLE);
                        mBtnSubmit.setText(btnStr);
                        mBtnSubmit.setTag(SupplyDic.getNextStatus(status));
                    }

                    userFragment.setData(bean.getSjimg(),bean.getSjnick(),
                            bean.getXiadanNumber(),bean.getJiedanNumber(),bean.getScore(),bean.getSjmobile());

                    break;
                case BaseDic.IdentityType.DRIVING_TYPE:
                    mTvLocal.setVisibility(View.GONE);
                    initToolbar(ConveyanceDic.getStatusTitle(status));
                    mTvStatus.setText(ConveyanceDic.getStatusStr(status));
                    btnStr = ConveyanceDic.getStatusBtn(status);
                    if (StringUtils.isEmpty(btnStr)) mBtnSubmit.setVisibility(View.GONE);
                    else {
                        mBtnSubmit.setVisibility(View.VISIBLE);
                        mBtnSubmit.setText(btnStr);
                        mBtnSubmit.setTag(ConveyanceDic.getNextStatus(status));
                    }

                    if(status == ROAD_STATUS || status == SH_STATUS || status == COMPLATE_STATUS) {
                        if("1".equals(bean.getIs_huidan()))
                            mBtnPic.setVisibility(View.GONE);
                        else
                            mBtnPic.setVisibility(View.VISIBLE);
                    }
                    userFragment.setData(bean.getHzimg(),bean.getHznick(),
                            bean.getXiadanNumber(),bean.getJiedanNumber(),bean.getScore(),bean.getHzmobile());

                    break;
            }


            if(status == COMPLATE_STATUS && "1".equals(bean.getIs_comment())){
                mBtnSubmit.setVisibility(View.GONE);
            }

            if (status == DZF_STATUS) {
                findViewById(R.id.lyt_add).setVisibility(View.VISIBLE);
                mTvTotal2.setVisibility(View.GONE);
            } else {
                findViewById(R.id.lyt_add).setVisibility(View.GONE);
                mTvTotal2.setVisibility(View.VISIBLE);
            }

            if (showcount == 0)
                beginDialog();// 进入时弹框

            showcount++;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.refreshWaybill(waybillId);
    }

    @Override
    public void initParams() {
        status = getIntent().getIntExtra("status", CANEL_CZ_STATUS);
        waybillId = getIntent().getStringExtra("data");
    }

    @Override
    public void initView() {

        new QuestionPresenter(this);
        lsNews = new ArrayList<>();

        mLvAdapter = new RecyclerWaybillAdapter(this, lsNews);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.setAdapter(mLvAdapter);
        supplyFragment = (SupplyFragment) getSupportFragmentManager().findFragmentByTag("supply");
        userFragment = (UserFragment) getSupportFragmentManager().findFragmentByTag("user");

        findViewById(R.id.tv_jia).setVisibility(View.GONE);

        makePayWayPopup();
        makeCanelDialog();
        makeCashDialog();
        makePayDialog();
        makePayPopup();
        makeKeywordPopup();
        makeResultDialog();
        makeDefineDialog();
        makeComplateDialog();
        makeInputDialog();

        if(!isrun)
            timer.schedule(task,500,5000);
    }

    TimerTask task= new TimerTask() {
        @Override
        public void run() {
            isrun = true;
            presenter.refreshWaybill(waybillId);
        }
    };


    public void makePayPopup(){
        String price = "";
        if(bean != null) price = bean.getCostByType();
        popupWindowPay = SupplyPopup.makePopupPayOption(this,price,this);
        popupWindowPay.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f; // 0.0-1.0
                getWindow().setAttributes(lp);
            }
        });
    }

    public void makePayWayPopup(){
        popupWindowPayWay = SupplyPopup.makePopupPayWayOption(this,this);
    }

    void makeCanelDialog(){
        caneldialog = new NormalDialog(this);
        caneldialog.content("您找到车子了吗，要不再等等？")
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","确定"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        caneldialog.cancel();
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        presenter.cancel(waybillId);
                    }
                });
    }

    void makeCashDialog(){
        if(cashdialog != null) return;
        cashdialog = new NormalDialog(this);
        cashdialog.content("货主已经支付运费，为了保证货物安全，请您支付100块押金。货主确认货到后，押金将返还到您的钱包。")
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","确定"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        hideDialog("cashdialog");
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        hideDialog("cashdialog");
                        if(popupWindowPay == null) return;
                        //  支付押金
                        payType = "3";
                        ((TextView)popupWindowPay.getContentView().findViewById(R.id.tv_total)).setText("￥100");
                        popupWindowPay.getContentView().findViewById(R.id.tv_tip).setVisibility(View.GONE);
                        showDialog("popupWindowPay");


                    }
                });
    }

    void makePayDialog(){
        payDialog = new NormalDialog(this);
        payDialog.isTitleShow(false)
                .content("线上支付送货物保险，为了保障您的货物安全，请线上支付。")
                .style(STYLE_TWO)
                .btnText(new String[]{"取消","支付"})
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        hideDialog("payDialog");
                    }
                },new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        findViewById(R.id.btn_submit).performClick();
                        hideDialog("payDialog");
                    }
                });
    }

    void makeResultDialog(){
        payResultDialog = new NormalDialog(this);
        payResultDialog.title("成功")
                .content("优质的信誉师傅，上面提货要准时哦，装货完成，记得点击【确认提货】哟")
                .style(STYLE_TWO)
                .btnText(new String[]{"好滴，记住了"})
                .cornerRadius(8)
                .btnNum(1)
                .setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                hideDialog("payResultDialog");
            }
        });
    }

    void makeDefineDialog(){
        defineDialog = new NormalDialog(this);
        defineDialog.title("确认收货")
                .content("确认收货后，平台将运费结算给货运司机")
                .btnText(new String[]{"取消","确认收货"})
                .style(STYLE_TWO)
                .dimEnabled(true)
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        hideDialog("defineDialog");
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        isComplate = true;
                        presenter.changeStatus(COMPLATE_STATUS+"",waybillId);
                        hideDialog("defineDialog");
                    }
                });
    }

    void makeComplateDialog(){
        complateDialog = new NormalDialog(this);
        complateDialog.title("运输完成")
                .content("运费已结算给货运司机\n请对本次服务的司机做个评价。")
                .btnText(new String[]{"有空再说","评价"})
                .style(STYLE_TWO)
                .dimEnabled(true)
                .setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        hideDialog("complateDialog");
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        jumpReply();
                        hideDialog("complateDialog");
                    }
                });
    }

    public void makeKeywordPopup(){
        final RecyclerKeyboardAdapter mAdapter = new RecyclerKeyboardAdapter(this,pwdDatas);
        popupWindowKeyword = MinePopup.makePopupPayTxOption(this, mAdapter, this, new KeyboardUtil.KeyBoardListener() {
            @Override
            public void onChange() {
                if(mAdapter.getDatas().size() <= 6)
                    mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onComplete() {
                presenter.QianbaoPay(payType,waybillId,mAdapter.getData());
                hideDialog("popupWindowKeyword");
//                }else
//                    ActivityUtils.toast("密码错误");
            }
        });
    }

    void makeInputDialog(){
        inputDialog = new BaseInputDialog(this);
        inputDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                inputDialog.cancel();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                presenter.jiajia(inputDialog.getPrice(),waybillId);
            }
        });
    }




    @Override
    public void onBackPressed() {
        ActivityUtils.startActivity(this, HostActivity.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
                ActivityUtils.startActivity(this, HostActivity.class);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_waybill;
    }

    @Override
    public void doShow(WayBillDetailBean bean) {
        if(bean != null) {
            this.bean = bean;
            status = StringUtils.parseInt(bean.getWaystate());
            lsNews.clear();
            if (bean != null && bean.getWuliulist() != null) {
                lsNews.addAll(bean.getWuliulist());
            }
            mLvAdapter.notifyDataSetChanged();
            initData();

            String price = "";
            if (bean != null) price = bean.getCostByType();
            //((TextView) popupWindowPay.getContentView().findViewById(R.id.tv_total)).setText("￥" + price);
            complateDialog.content("运费" + price + "已结算给货运司机\n请对本次服务的司机做个评价。");
            if (isComplate)
                if (status == COMPLATE_STATUS) {
                    isComplate = false;
                    complateDialog.show();
                }
        }
    }

    @Override
    public void refreshView() {
        initData();
    }

    @Override
    public void hideDialog(String type) {
        if(type.equals("popupWindowPay")){
            popupWindowPay.dismiss();
        }else if(type.equals("popupWindowPayWay")){
            popupWindowPayWay.dismiss();
        }else if(type.equals("popupWindowKeyword")){
            popupWindowKeyword.dismiss();
        }else if(type.equals("caneldialog")){
            caneldialog.cancel();
            finish();
        }else if(type.equals("payDialog")){
            payDialog.cancel();
        }else if(type.equals("cashdialog")){
            cashdialog.cancel();
        }else if(type.equals("payResultDialog")){
            payResultDialog.cancel();
        }else if(type.equals("defineDialog")){
            defineDialog.cancel();
        }else if(type.equals("complateDialog")){
            complateDialog.cancel();
        }else if(type.equals("inputDialog")){
            inputDialog.cancel();
        }
    }

    @Override
    public void showDialog(String type) {
        if(type.equals("caneldialog")){
            caneldialog.show();
        }else if(type.equals("payDialog")){
            payDialog.show();
        }else if(type.equals("cashdialog")){
            cashdialog.show();
        }else if(type.equals("popupWindowPay")){
            if(popupWindowPay == null) return;
            popupWindowPay.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);;
            WindowManager.LayoutParams lp = getWindow()
                    .getAttributes();
            lp.alpha = 0.5f; // 0.0-1.0
            getWindow().setAttributes(lp);
        }else if(type.equals("popupWindowPayWay")){
            popupWindowPayWay.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);;
        }else if(type.equals("popupWindowKeyword")){
            popupWindowKeyword.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        }else if(type.equals("showPayResultYJ")){
            payResultDialog.title("支付成功")
                    .content("优质的信誉师傅，上面提货要准时哦，装货完成，记得点击【确认提货】哟")
                    .btnText(new String[]{"好滴，记住了"});
            payResultDialog.show();
        }else if(type.equals("showTH")){
            payResultDialog.title("起程运输咯")
                    .content("运输交给师傅您，我们很放心\n速拉回程车将竭诚为您服务！")
                    .btnText(new String[]{"好的"});
            payResultDialog.show();
        }else if(type.equals("showHD")){
            payResultDialog.title("谢谢师傅辛苦了")
                    .content("稍后货主确认后，运费打到您的钱包里，日常运输多注意身体！")
                    .btnText(new String[]{"好的"});
            payResultDialog.show();
        }else if(type.equals("defineDialog")){
            defineDialog.show();
        }else if(type.equals("complateDialog")){
            complateDialog.show();
        }else if(type.equals("inputDialog")){
            inputDialog.show();
        }
    }

    @Override
    public void beginDialog() {
        if (status == DZF_STATUS) {
            showDialog("payDialog");
        } else if (status == YAJIN_STATUS && BaseDic.IdentityType.DRIVING_TYPE.equals(UniApplication.getInstance().getType())) {
            showDialog("cashdialog");
        } else if (status == DZF_STATUS && BaseDic.IdentityType.DRIVING_TYPE.equals(UniApplication.getInstance().getType())){

        }
    }

    @Override
    public void complateLoaded() {
        UtilMethod.dismissProgressDialog(this);
    }

    @Override
    public String getStatus() {
        return status+"";
    }

    @Override
    public void setStatus(String status) {
        this.status = StringUtils.parseInt(status);
    }

    @Override
    public String getPayType() {
        return payType;
    }

    @Override
    public void setPayType(String paytype) {
        this.payType = paytype;
    }

    @Override
    public String getWayBillid() {
        return waybillId;
    }

    @Override
    public void jumpMap() {
        Bundle bundle = new Bundle();
        bundle.putString("lng", bean.getSjlng());
        bundle.putString("lat", bean.getSjlat());
        bundle.putString("title", bean.getSjnick());
        ActivityUtils.startActivity(this,MapGdActivity.class,bundle);
    }

    @Override
    public void jumpTel() {

    }

    @Override
    public void jumpHuidan() {
        Bundle bundle = new Bundle();
        bundle.putString("waybillid",waybillId);
        ActivityUtils.startActivity(this,HuidanActivity.class,bundle);
    }

    @Override
    public void jumpReply() {
        Bundle bundle = new Bundle();
        bundle.putString("waybillid",waybillId);
        ActivityUtils.startActivity(this,ReplyActivity.class,bundle);

    }

    @Override
    public void jumpForgot() {
        ActivityUtils.startActivity(this,PasswordPayActivity.class);
    }

    @Override
    public void setPresenter(QuestionContract.Presenter presenter) {
        this.presenter = presenter;
    }
}
